/**
 * Copyright 2008 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kiff.enumerator;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Struts Enum Type Converter.
 * @author Adam
 * @version $Id: StrutsEnumConverter.java 73 2008-12-02 06:28:25Z a.ruggles $
 */
public class StrutsEnumConverter extends StrutsTypeConverter {
    /**
     * The <code>Logger</code> is used by the application to generate a log messages.
     */
    private final Logger logger = LoggerFactory.getLogger(StrutsEnumConverter.class);

    /**
     * @see org.apache.struts2.util.StrutsTypeConverter#convertFromString(
     * java.util.Map, java.lang.String[], java.lang.Class)
     */
    @Override @SuppressWarnings("unchecked")
	public Object convertFromString(final Map context, final String[] values, final Class toClass) {
    	if (values == null || values.length != 1) {
            return null;
        }
        try {
            return Enum.valueOf(toClass, values[0]);
        } catch (IllegalArgumentException illegalArgumentEx) {
            logger.error("Error converting value [" + values[0] + "] to Enum ", illegalArgumentEx);
        } catch (NullPointerException nullPointerEx) {
            logger.error("Error converting value [" + values[0] + "] to Enum ", nullPointerEx);
        }
        return null;
	}

	/**
	 * @see org.apache.struts2.util.StrutsTypeConverter#convertToString(java.util.Map, java.lang.Object)
	 */
	@Override @SuppressWarnings("unchecked")
	public String convertToString(final Map context, final Object obj) {
		if (obj instanceof Enum) {
            return ((Enum) obj).name();
        }
        return "";
	}

}
